package com.nowcoder.community.util;/**
 * @description:
 * @Author HP
 * @create 2021/12/16 14:23
 */

import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author HP
 * @create 2021-12-16 14:23
 * @desc 用于过滤敏感词的类
 **/
@Component
public class SensityFilter {
    private static Logger logger= LoggerFactory.getLogger(SensityFilter.class);
    //替换符号
    private static final String REPLACEMEWNT="***";
    //根节点
    private TrieNode root=new TrieNode();

    @PostConstruct
    public void init(){
        try(
            InputStream ips= this.getClass().getClassLoader().getResourceAsStream("sensitive-words.txt");
            BufferedReader reader=new BufferedReader(new InputStreamReader(ips));
                ) {
            String keyword;
            while ((keyword= reader.readLine())!=null){
                this.addKeyWord(keyword);
            }

        } catch (Exception e) {
            logger.error("读取敏感词文件失败："+e.getMessage());
        }
    }

    //将敏感词添加进前缀树中
    private void addKeyWord(String keyword){
        TrieNode tempNode=root;
        for (int i = 0; i < keyword.length(); i++) {
            Character c=keyword.charAt(i);
            TrieNode subNode=root.getSubNode(c);
            if (subNode==null){
                subNode=new TrieNode();
                tempNode.addSubNodes(c,subNode);
            }
            tempNode=tempNode.getSubNode(c);
            if (i==keyword.length()-1){
                tempNode.setKeyEnd(true);
            }
        }
    }

    /**
     *
     * @param text:代过滤文本
     * @return：过滤后的文本
     */
    public String filter(String text){
        if (StringUtils.isBlank(text)){
            return null;
        }
        StringBuilder sb=new StringBuilder();
        //指针一，指向前缀树
        TrieNode tempNode=root;
        //指针2,3指向text
        int begin=0,position=0;
        while (position<text.length()){
            char c=text.charAt(position);
            if (isSymbol(c)){
                //若指针1指向根节点，则将此符号计入结果，指针2向下走一步
                if (tempNode==root){
                    sb.append(c);
                    begin++;
                }
                position++;
                continue;
            }
            //检查下级节点
            tempNode=tempNode.getSubNode(c);
            if (tempNode==null){
                //以begin开头的字符不是敏感词
                sb.append(text.charAt(begin));
                position=++begin;
                tempNode=root;
            }else if (tempNode.isKeyEnd){
                //发现敏感词
                sb.append(REPLACEMEWNT);
                begin=++position;
                tempNode=root;
            }else {
                position++;
            }
        }
        sb.append(text.substring(begin));
        return sb.toString();
    }

    //判断特殊符号
    private boolean isSymbol(char c){
        //0x2E80,0x9FFF是东南亚文字
        return !CharUtils.isAsciiAlphanumeric(c) && (c<0x2E80||c>0x9FFF);
    }

    private class TrieNode{
        //关键词结束标识
        private boolean isKeyEnd=false;
        //当前节点的子节点（key是下级字符，value是下级节点\
        Map<Character,TrieNode>subNodes=new HashMap<>();

        public boolean isKeyEnd() {
            return isKeyEnd;
        }

        public void setKeyEnd(boolean keyEnd) {
            isKeyEnd = keyEnd;
        }

        //添加子节点
        public void addSubNodes(Character c,TrieNode node) {
            subNodes.put(c,node);
        }

        //获取子节点
        public TrieNode getSubNode(Character c){
            return subNodes.get(c);
        }

    }
}
